package org.fig.dependency.injection;

import org.fig.ioc.overview.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;
import javax.jws.soap.SOAPBinding;

/**
 * @Description: 基于字段注入
 * @Author: Flynn Vanderboom
 * @Data: 2021/6/20 22:18
 */

public class AnnotationDependencyFieldInjectionDemo {

    //底下@Bean注入
    @Autowired
    private UserHolder userHolder;
    //@Autowired 会忽略掉静态字段
    //@Autowired
    //private static UserHolder userHolder;




    @Resource
    private UserHolder userHolder2;
    public static void main(String[] args) {
        //创建BeanFactory容器
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        //注册  配置类   ---->Spring Bean
        context.register(AnnotationDependencyFieldInjectionDemo.class);


        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);

        String xmlResourcePath = "classpath:META-INF/dependency-lookup-context.xml";

        //加载XML资源，解析并且生成BeanDefinition
        reader.loadBeanDefinitions(xmlResourcePath);


        //启动上下文
        context.refresh();

        //依赖查找 AnnotationDependencyFieldInjectionDemo
        AnnotationDependencyFieldInjectionDemo demo = context.getBean(AnnotationDependencyFieldInjectionDemo.class);

        //通过@Autowired字段关联
        UserHolder userHolder = demo.userHolder;
        //通过@Resource字段关联
        UserHolder userHolder2 =  demo.userHolder2;

        System.out.println("userHolder: "+userHolder);
        System.out.println("userHolder2: "+userHolder2);
        System.out.println(userHolder==userHolder2);

        //关闭上下文
        context.close();
    }


    @Bean
    public UserHolder userHolder(User user) {
        return new UserHolder(user);
    }


}
